const express = require('express');
const { body, query } = require('express-validator');
const productController = require('../controllers/productController');
const { authenticate, authorize } = require('../middleware/auth');
const { uploadProductImages, uploadCategoryImage, handleUploadError } = require('../middleware/upload');
const { validate } = require('../middleware/validation');

const router = express.Router();

// 商品验证规则
const productValidation = [
    body('name')
        .notEmpty()
        .withMessage('商品名称不能为空')
        .isLength({ max: 200 })
        .withMessage('商品名称不能超过200个字符'),
    body('sku')
        .notEmpty()
        .withMessage('SKU不能为空')
        .isLength({ max: 100 })
        .withMessage('SKU不能超过100个字符'),
    body('price')
        .isFloat({ min: 0 })
        .withMessage('价格必须为非负数'),
    body('stock')
        .isInt({ min: 0 })
        .withMessage('库存必须为非负整数'),
    body('categoryId')
        .isInt({ min: 1 })
        .withMessage('必须选择有效的分类')
];

// 分类验证规则
const categoryValidation = [
    body('name')
        .notEmpty()
        .withMessage('分类名称不能为空')
        .isLength({ max: 100 })
        .withMessage('分类名称不能超过100个字符')
];

// 查询验证规则
const queryValidation = [
    query('page')
        .optional()
        .isInt({ min: 1 })
        .withMessage('页码必须为正整数'),
    query('limit')
        .optional()
        .isInt({ min: 1, max: 100 })
        .withMessage('每页数量必须在1-100之间'),
    query('minPrice')
        .optional()
        .isFloat({ min: 0 })
        .withMessage('最低价格必须为非负数'),
    query('maxPrice')
        .optional()
        .isFloat({ min: 0 })
        .withMessage('最高价格必须为非负数')
];

// 公共路由
router.get('/', queryValidation, validate, productController.getProducts);
router.get('/categories', productController.getCategories);
router.get('/:id', productController.getProduct);

// 管理员路由
router.post(
    '/',
    authenticate,
    authorize('admin'),
    uploadProductImages,
    handleUploadError,
    productValidation,
    validate,
    productController.createProduct
);

router.put(
    '/:id',
    authenticate,
    authorize('admin'),
    uploadProductImages,
    handleUploadError,
    productValidation,
    validate,
    productController.updateProduct
);

router.delete(
    '/:id',
    authenticate,
    authorize('admin'),
    productController.deleteProduct
);

router.post(
    '/categories',
    authenticate,
    authorize('admin'),
    uploadCategoryImage,
    handleUploadError,
    categoryValidation,
    validate,
    productController.createCategory
);

module.exports = router;